package net.diaowen.dwsurvey.controller;

import org.apache.commons.lang.StringUtils;
import org.apache.logging.log4j.core.util.UuidUtil;
import org.apache.shiro.web.servlet.ShiroHttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

@Controller
@RequestMapping("/up")
public class UploadController {
	/**
	 * 上传文件数据，安全存储
	 * /WebRoot/WEB-INF/upfile
	 */
    @RequestMapping("/up-file.do")
    @ResponseBody
    public String uploadFile(HttpServletRequest request,HttpServletResponse response) {
        String savePath = File.separator+"file" + File.separator + "images" + File.separator;

        return proUpfile((ShiroHttpServletRequest) request, savePath);
    }


    @RequestMapping("/up-file-wb.do")
    @ResponseBody
    public String uploadFileWb(HttpServletRequest request,HttpServletResponse response) {
        String savePath = File.separator+"WEB-INF"+File.separator+"upload" + File.separator;

        return proUpfile((ShiroHttpServletRequest) request, savePath);
    }


    private String proUpfile(ShiroHttpServletRequest request, String savePath) {
        ShiroHttpServletRequest shiroRequest = request;
        StringBuffer sb = new StringBuffer();
        Map<String, String> files = new HashMap<String, String>();
        String rootPath = shiroRequest.getSession().getServletContext().getRealPath("/");

        File dirFile = new File(rootPath+savePath);
        if  (!dirFile .exists()  && !dirFile .isDirectory()) {
            dirFile .mkdir();
        }
        //创建一个通用的多部分解析器
        try{

            CommonsMultipartResolver commonsMultipartResolver = new CommonsMultipartResolver();
            MultipartHttpServletRequest multiRequest = commonsMultipartResolver.resolveMultipart((HttpServletRequest) shiroRequest.getRequest());

            //CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(shiroRequest.getSession().getServletContext());
            //判断 request 是否有文件上传,即多部分请求

            System.setProperty("sun.jnu.encoding","utf-8");
            //转换成多部分request
            //取得request中的所有文件名
            Iterator<String> iter = multiRequest.getFileNames();
            while(iter.hasNext()){
                //记录上传过程起始时的时间，用来计算上传时间
                int pre = (int) System.currentTimeMillis();
                //取得上传文件
                MultipartFile file = multiRequest.getFile(iter.next());
                if(file != null){
                    //取得当前上传文件的文件名称
                    String myFileName = file.getOriginalFilename();
                    //如果名称不为“”,说明该文件存在，否则说明该文件不存在
                    if(myFileName.trim() !=""){
                        System.out.println(myFileName);
                        //重命名上传后的文件名
                        String fileName = file.getOriginalFilename();
                        //定义上传路径
                        String path = savePath + fileName;
                        System.out.println(path);
                        File localFile = new File(rootPath+path);
                        file.transferTo(localFile);
                        files.put(fileName, path);
                    }
                }
                //记录上传该文件后的时间
                int finaltime = (int) System.currentTimeMillis();
                System.out.println(finaltime - pre);
            }
            if(files.size()>0){
                sb.append("{\"success\":\"true\"");
                sb.append(",\"filename\":\"");

                for (String key: files.keySet()) {
                    sb.append(key);
                    sb.append("  ");
                }
                sb.append("\"");
                sb.append(",\"location\":\"");

                for (String key: files.keySet()) {
                    sb.append(files.get(key) + ";");
                }

                if(sb!=null&& StringUtils.isNotBlank(sb.toString())&&sb.toString().endsWith(";")){
                    sb.deleteCharAt(sb.length()-1);
                }

                sb.append("\"");
                sb.append("}");
            }else{
                sb.append("{\"success\":\"false\",\"error\":\"未收到上传文件\"}");
            }
        }catch (Exception e){
            sb.append("{\"success\":\"false\",\"error\":\"上传失败\"}");
            e.printStackTrace();
        }
        return sb.toString();
    }





}
